/** 
  课程成绩管理
*/
<template>
  <div class="final-assess-result-container">
    <!-- 课程列表开始 -->
    <div v-if="indexKey === 1">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <!-- 学年学期 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntrySwitch.semester')">
              <calendar-select v-model="queryForm.calendarId" @load-done="calendarIdLoadDone" clearable :placeholder="$t('common.pla.pleaseSelect')"></calendar-select>
            </el-form-item>
          </el-col>
          <!-- 发布状态 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.postStatus')">
              <el-select v-model="queryForm.releaseType" @change="changeReleaseType" style="width: 100%">
                <el-option
                  v-for="item in options.releaseType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 课程代码/名称 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.teachingClassCode')">
              <el-select
                v-model.trim="queryForm.courseCode"
                :remote-method="remoteMethod"
                filterable
                remote
                clearable
                :placeholder="$t('common.pla.pleaseInput')"
                style="width:100%">
                <el-option
                  v-for="item in options.courseCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 50px;">
          <!-- 课程序号 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.courseCode')">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="queryForm.teachingClassCode" :maxlength="32" clearable></el-input>
            </el-form-item>
          </el-col>
          <!-- 开课学院 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntrySwitch.startCollege')">
              <el-select v-model="queryForm.faculty" clearable style="width: 100%">
                <el-option
                  v-for="item in options.faculty"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 课程类别 -->
          <el-col :span="8">
            <el-form-item :label="$t('scoreEntryMana.courseType')">
              <el-select v-model="queryForm.courseLabelId" clearable style="width: 100%">
                <el-option
                  v-for="item in options.courseLabelId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="height: 50px;">
          <!-- 校区 -->
          <el-col :span="8">
            <el-form-item :label="$t('courseScoreMana.campus')">
              <el-select v-model="queryForm.campus" clearable style="width: 100%">
                <el-option
                  v-for="item in options.campus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{ $t('scoreEntryMana.courseList') }}</h1>
        <div class="sub-title">
          <div class="float-left" style="margin-bottom: 20px;">
            <el-input
              clearable
              v-model="queryForm.searchText"
              :placeholder="$t('courseScoreMana.placeholderSearch')"
              style="width:250px"
              @change="onSubmit"
              @keyup.enter.native="onSubmit">
                <i slot="prefix"
                  class="el-icon-search"
                  style="margin-top:10px;cursor:pointer"
                  @click="onSubmit">
                </i>
            </el-input>
          </div>
          <!-- 已发布开始 -->
          <div class="float-right" style="display: flex;" v-if="queryForm.releaseType === 'Y'">
            <!-- 批量打印 -->
            <el-dropdown trigger="click" @command="batchPrinting" style="margin-right: 10px;">
              <el-button type="primary">
                {{ $t('courseScoreMana.batchPrinting') }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="overall">{{ $t('courseScoreMana.overallEvalScoreSheet') }}</el-dropdown-item>
                <el-dropdown-item command="subItemOverall">{{ $t('courseScoreMana.subItemOverallEvalScoreSheet') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 批量导出 -->
             <el-dropdown trigger="click" @command="batchExport">
              <el-button type="primary">
                {{ $t('courseScoreMana.batchExport') }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="overall">{{ $t('courseScoreMana.overallEvalScoreSheet') }}</el-dropdown-item>
                <el-dropdown-item command="subItemOverall">{{ $t('courseScoreMana.subItemOverallEvalScoreSheet') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 总评成绩表 -->
            <el-button v-if="permitToTotalEvalScoreSheet" @click="totalEvalScoreSheet()">{{ $t('courseScoreMana.overallEvalScoreSheet') }}</el-button>
            <!-- 总评成绩（分项） -->
            <el-button v-if="permitToSubTotalEvalScoreSheet" @click="subEvalScoreSheet()">{{ $t('courseScoreMana.subItemOverallEvalScoreSheet') }}</el-button>
          </div>
          <!-- 已发布结束 -->
          <!-- 未发布开始 -->
          <div class="float-right" style="display: flex;" v-else>
            <!-- 部分发布课程 -->
            <el-button v-if="permitToPartReleased" @click="partReleaseCourse()">{{ $t('courseScoreMana.partReleaseCourse') }}</el-button>
            <!-- 指定录入人 -->
            <el-button v-if="permitToDesignatedEntry" @click="designatedEntry()">{{ $t('courseScoreMana.designatedEntry') }}</el-button>
            <!-- 取消指定 -->
            <el-button v-if="permitToCancelPoint" @click="cancelPoint()">{{ $t('courseScoreMana.cancelPoint') }}</el-button>
            <!-- 空白登分表 -->
            <el-button v-if="permitToBlankScoreTable" @click="blankScoreTable()">{{ $t('scoreEntryMana.blankScoreSheet') }}</el-button>
          </div>
          <!-- 未发布结束 -->
        </div>
        <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <!-- 课程序号 -->
          <edu-table-column :label="$t('scoreEntryMana.courseNum')" prop="teachingClassCode"></edu-table-column>
          <!-- 课程代码 -->
          <edu-table-column :label="$t('scoreEntryMana.courseCode')" prop="courseCode"></edu-table-column>
          <!-- 课程名称 -->
          <edu-table-column :label="$t('scoreEntryMana.courseName')" prop="courseName"></edu-table-column>
          <!-- 课程类别 -->
          <edu-table-column :label="$t('scoreEntryMana.courseType')" prop="courseLabelName"></edu-table-column>
          <!-- 开课学院 -->
          <edu-table-column :label="$t('scoreEntrySwitch.startCollege')" prop="facultyI18n"></edu-table-column>
          <!-- 校区 -->
          <edu-table-column :label="$t('courseScoreMana.campus')" prop="campusI18n"></edu-table-column>
          <!-- 教师 -->
          <edu-table-column :label="$t('scoreEntryMana.tearcher')" prop="headTeacherName">
            <template slot-scope="scope">
              {{ scope.row.headTeacher }}{{ scope.row.headTeacherName }}
            </template>
          </edu-table-column>
          <!-- 录入人 -->
          <edu-table-column :label="$t('courseScoreMana.entryPerson')" prop="importUserName">
            <template slot-scope="scope">
              {{ scope.row.importUserCode }}{{ scope.row.importUserName }}
            </template>
          </edu-table-column>
          <!-- 指定录入人 -->
          <edu-table-column :label="$t('courseScoreMana.designatedEntry')" prop="assignedName">
            <template slot-scope="scope">
              {{ scope.row.assignedCode }}{{ scope.row.assignedName }}
            </template>
          </edu-table-column>
          <!-- 已发布人数/总人数 -->
          <edu-table-column :label="queryForm.releaseType === 'Y' ? $t('scoreEntryMana.numOfPeople') : $t('courseScoreMana.alreadyPublishNum')" prop="peopleNum" :width="queryForm.releaseType === 'N' ? '150' : '50'">
            <template slot-scope="scope">
              <span v-if="queryForm.releaseType === 'N'">
                {{ scope.row.releaseNum ? scope.row.releaseNum : 0 }}/{{ scope.row.peopleNum ? scope.row.peopleNum : 0 }}
              </span>
              <span v-if="queryForm.releaseType === 'Y'">
                {{ scope.row.peopleNum ? scope.row.peopleNum : 0 }}
              </span>
            </template>
          </edu-table-column>
          <!-- 学分 -->
          <edu-table-column :label="$t('scoreEntryMana.credit')" prop="credits"></edu-table-column>
          <!-- 课时 -->
          <edu-table-column :label="$t('courseScoreMana.courseTime')" prop="schoolHour"></edu-table-column>
          <!-- 查看 -->
          <edu-table-column :label="$t('common.text.operation')" prop="status" fit width="120px">
            <template slot-scope="scope">
              <!-- 查看 -->
              <el-button v-if="permitToDetail" type="text" @click="selectCourseInfo(scope.row)">{{ $t('scoreMangementBase.select') }}</el-button>
              <!-- 取消发布 -->
              <el-button v-if="permitToUnpublish && queryForm.releaseType === 'Y'" type="text" @click="unPublish(scope.row)">{{ $t('courseScoreMana.unPublish') }}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 课程列表结束 -->
    <!-- 部分发布课程开始 -->
    <div v-if="indexKey === 2">
      <part-of-course-release @refresh-main-page="refreshMainPage()"></part-of-course-release>
    </div>
    <!-- 部分发布课程结束 -->
    <!-- 空白登分表开始 -->
    <div v-if="indexKey === 3">
      <blank-sheet-score :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></blank-sheet-score>
    </div>
    <!-- 空白登分表结束 -->
    <!-- 查看开始 -->
    <div v-if="indexKey === 4">
      <select-score :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></select-score>
    </div>
    <!-- 查看结束 -->
    <!-- 总评成绩表开始 -->
    <div v-if="indexKey === 5">
      <overall-assess-score-sheet :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></overall-assess-score-sheet>
    </div>
    <!-- 总评成绩表结束 -->
    <!-- 总评成绩表（分项）开始 -->
    <div v-if="indexKey === 6">
      <subItem-overall-assess-score-sheet :detailInfo="detailInfo" @refresh-main-page="refreshMainPage()"></subItem-overall-assess-score-sheet>
    </div>
    <!-- 总评成绩表（分项）结束 -->
    <!-- 指定录入人开始 -->
    <el-dialog
      ref="teacherDialog"
      :before-close="beforeClose"
      :title="title"
      width="30%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="90px" style="padding-right: 30px;">
        <el-row>
          <el-col :span="24">
            <!-- 教师 -->
            <el-form-item
              :label="$t('scoreEntryMana.tearcher') + '：'"
              prop="selectTeacherName"
              :rules="[{ required: true, message: $t('scoreEntryMana.requireTeacher'), trigger: 'blur' }]">
              <el-select
                v-model="dialogForm.selectTeacherName"
                :placeholder="$t('score.pleaseInputKey')"
                :remote-method="teacherRemoteMethod"
                filterable
                remote
                style="width: 100%;">
                <el-option
                  v-for="item in options.teacherList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <span style="float: left">{{ item.label }}{{ "(" + item.value + ")" }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.facultyI18n }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <template>
          <el-button @click="cancel('dialogForm')">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirm('dialogForm')">{{ $t('common.btn.confirm') }}</el-button>
        </template>
      </span>
    </el-dialog>
    <!-- 指定录入人结束 -->
    <!-- 指定录入人二次确认弹框开始 -->
    <el-dialog
      :visible.sync="settingEnterPerson"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="$t('scoreMangementBase.prompt')"
      width="400px">
      <span>{{ $t('courseScoreMana.confirmDesignatedEntry') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingEnterPerson = false">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirmSettingEnterPerson">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 指定录入人二次确认弹框结束 -->
     <!-- 取消发布二次却认提示开始 -->
    <el-dialog
      :visible.sync="settingUnpublishEnter"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="$t('scoreMangementBase.prompt')"
      width="400px">
      <span>{{ unpublishEnterContant }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingUnpublishEnter = false">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="unPublishEnter">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 取消发布二次却认提示结束 -->
    <!-- 短信发送开始 -->
    <el-dialog
      :before-close="beforeCloseMsg"
      :title="$t('scoreEntryMana.messageValidate')"
      width="70%"
      :visible.sync="dialogVisibleMsg"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogFormMsg" label-position="right" ref="dialogFormMsg" label-width="120px">
        <el-row>
          <el-col :span="16">
            <!-- 短信验证码 -->
            <el-form-item
              :label="$t('scoreEntryMana.verificationCode') + '：'"
              prop="verificationCode"
              :rules="[{ required: true, message: $t('scoreEntryMana.requireVerificationCode'), trigger: 'blur' },{ validator: validateMessage, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="dialogFormMsg.verificationCode" :maxlength="6" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 密码序号 -->
            <el-form-item :label="$t('scoreEntryMana.passwordNum') + '：'">{{ passwordNum }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeCloseMsg('dialogFormMsg')">{{ $t('common.btn.cancel') }}</el-button>
        <el-button type="primary" @click="confirmMsg('dialogFormMsg')">{{ $t('common.btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!-- 短信发送结束 -->
  </div>
</template>
<script>
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
import { findTeacherList } from 'common/src/api/resource/teachers';
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
import partOfCourseRelease from './partOfCourseRelease';
import blankSheetScore from './blankSheetScore';
import selectScore from './selectScore';
import overallAssessScoreSheet from './overallAssessScoreSheet';
import subItemOverallAssessScoreSheet from './subItemOverallAssessScoreSheet';
export default {
  components: {
    'part-of-course-release': partOfCourseRelease,
    'blank-sheet-score': blankSheetScore,
    'select-score': selectScore,
    'overall-assess-score-sheet': overallAssessScoreSheet,
    'subItem-overall-assess-score-sheet': subItemOverallAssessScoreSheet
  },
  data () {
    return {
      indexKey: 1,
      auths: [],
      userInfo: {},
      permitToPartReleased: false,
      permitToDesignatedEntry: false,
      permitToCancelPoint: false,
      permitToBlankScoreTable: false,
      permitToDetail: false,
      permitToTotalEvalScoreSheet: false,
      permitToSubTotalEvalScoreSheet: false,
      permitToUnpublish: false,
      multipleSelection: [],
      dataList: [],
      queryForm: {
        calendarId: '',
        releaseType: 'N',
        teachingClassCode: '',
        courseCode: '',
        faculty: '',
        courseLabelId: '',
        campus: '',
        searchText: '',
        pageNum_: 1,
        pageSize_: 20,
        total_: 0
      },
      options: {
        releaseType: [
          {
            key: 1,
            label: '未发布',
            value: 'N'
          },
          {
            key: 2,
            label: '已发布',
            value: 'Y'
          }
        ],
        faculty: [],
        courseLabelId: [],
        campus: [],
        teacherList: [],
        courseCodeList: []
      },
      detailInfo: {},
      title: '',
      dialogVisible: false,
      dialogForm: {
        selectTeacherName: ''
      },
      settingEnterPerson: false,
      settingUnpublishEnter: false,
      unpublishEnterContant: '', // 取消发布提示内容
      messageInfo: {},
      passwordNum: '05',
      dialogVisibleMsg: false,
      dialogFormMsg: {
        verificationCode: ''
      },
      unPublishPamas: null, // 取消发布参数
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
  },
  mounted() {
    if (this.queryForm.calendarId) {
      this.onSubmit()
    }
    this.initOptions()
  },
  methods: {
    calendarIdLoadDone() {
      this.onSubmit()
    },
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验短信验证码
    validateMessage(rule, value, callback) {
      let expReg = /^\d{6}$/
      if (!expReg.test(value)) {
        callback(new Error(this.$t('scoreEntryMana.validateMessage')))
      } else {
        callback()
      }
    },
    initOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: [
          "X_YX", // 学院
          "K_KCLB", // 课程类别
          "X_XQ" // 校区
        ]
      }
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            faculty: "X_YX", // 学院
            courseLabelId: "K_KCLB", // 课程类别
            campus: "X_XQ"
          },
          res.data,
          this.options
        )
      })
    },
    // 课程代码、名称搜索方法
    remoteMethod(val) {
      if (val !== '') {
        this.loading = true
        let lang = this.$store.getters.language
        scoreManagementApi.queryCourseInfoByCourseCode({
          courseCode: val
        }).then(res => {
          this.loading = false
          if (res.code == 200) {
            const list = res.data &&
              res.data.map(e => {
                let obj = {}
                obj.label = lang === 'cn' ? e.name + '(' + e.code + ')' : e.nameEn + '(' + e.code + ')'
                obj.value = e.code
                return obj
              })
            this.options.courseCodeList = list
          }
        })
      } else {
        this.options.courseCodeList = []
        this.queryForm.condition.courseCodeAndName = ''
      }
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    getListData() {
      scoreManagementApi.queryCourseScoreMana(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total_
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    reset() {
      for (let key in this.queryForm) {
        if (key === 'releaseType') {
          this.queryForm[key] = 'N'
        } else if (key !== 'calendarId' && key !== 'pageSize_' && key !== 'total_') {
          this.queryForm[key] = ''
        }
      }
      this.onSubmit()
    },
    // 修改发布状态
    changeReleaseType(val) {
      this.onSubmit()
    },
    // 批量打印
    batchPrinting(command) {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      let sourceType = command === 'overall' ? '0' : '1'
      let teachingClassIds = this.multipleSelection.map(value => {
        return value.teachingClassId
      })
      let params=`/api/scoremanagementservice/minorCourseGradeManageController/batchPrintMinorGradeTotalTable?calendarId=${this.queryForm.calendarId}&teachingClassIds=${teachingClassIds.toString()}&examType=2&language=${this.$store.getters.language || 'cn'}&sourceType=${sourceType}`
      window.open(params)
    },
    // 批量导出
    batchExport(command) {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      let sourceType = command === 'overall' ? '0' : '1'
      let teachingClassIds = this.multipleSelection.map(value => {
        return value.teachingClassId
      })
      let params=`/api/scoremanagementservice/minorCourseGradeManageController/batchExportMinorGradeTotalTable?calendarId=${this.queryForm.calendarId}&teachingClassIds=${teachingClassIds.toString()}&examType=2&language=${this.$store.getters.language || 'cn'}&sourceType=${sourceType}`
      window.open(params)
    },
    // 取消发布
    unPublish(row) {
      this.unPublishPamas = null
      let params = {
        "calendarId": this.queryForm.calendarId,
        "teachingClassId": row.teachingClassId,
        "courseCode": row.courseCode,
        "examType": "2"
      }
      this.unPublishPamas = params
      scoreManagementApi.checkHasGradeChange(params).then(res => {
        if (res.code === 200) {
          this.unpublishEnterContant = res.msg
          this.settingUnpublishEnter = true
        }
      })
    },
    // 确认取消发布 调短信发送
    unPublishEnter() {
      this.settingUnpublishEnter = false
      scoreManagementApi.sendMessage({
        "pushType": 0,
        "type": 1
      }).then(res => {
        if (res.code === 200) {
          this.messageInfo = res.data
          this.passwordNum = res.data.id
          this.title = this.$t('scoreEntryMana.messageValidate')
          this.dialogVisibleMsg = true
        }
      })
    },
    // 短信验证吗确认
    confirmMsg(dialogName) {
      this.$refs[dialogName].validate(valid => {
        if (valid) {
          scoreManagementApi.validateMessage({
            "id": this.messageInfo.id,
            "code": this.dialogFormMsg.verificationCode,
            "receiverCode": this.messageInfo.receiverCode
          }).then(res => {
            if (res.code === 200) {
              this.dialogFormMsg.verificationCode = ''
              this.$refs[dialogName].clearValidate()
              this.dialogVisibleMsg = false
              scoreManagementApi.cancelMinorPublish(this.unPublishPamas).then(res => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success', 
                    message: this.$t('courseScoreMana.unPublishSuccessfully')
                  })
                  this.onSubmit()
                  this.unPublishPamas = null
                }
              })
            }else{
              this.dialogFormMsg.verificationCode = ''
              this.$refs[dialogName].clearValidate()
              this.dialogVisibleMsg = false
              this.unPublishPamas = null
              return;
            }
          })
        }
      })
    },
    beforeCloseMsg() {
      this.dialogFormMsg.verificationCode = ''
      this.$refs['dialogFormMsg'].clearValidate()
      this.dialogVisibleMsg = false
      this.unPublishPamas = null
    },
    // 部分发布课程
    partReleaseCourse() {
      this.indexKey = 2
    },
    // 指定录入人
    designatedEntry() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 勾选数据中存在部分发布课程，则指定录入人失败，弹出“勾选课程中存在成绩已发布，不能指定录入人”
      let hasPartlyReleased = false
      // 若勾选数据中存在录入人
      let hasAssignedPerson = false
      // 若勾选的数据已经有指定录入人，二次弹框确认
      let alreadyAssigned = false
      this.multipleSelection.map(value => {
        if (value.assignedName) {
          alreadyAssigned = true
        }
        if (value.releaseNum > 0) {
          hasPartlyReleased = true
        }
        if (value.importUserName) {
          hasAssignedPerson = true
        }
      })
      // 勾选数据中存在部分发布课程，则指定录入人失败，弹出“勾选课程中存在成绩已发布，不能指定录入人”
      if (hasPartlyReleased) {
        this.$message.warning(this.$t('courseScoreMana.hasPartlyReleasedData'))
        return
      }
      // 勾选数据中已有录入人
      if (hasAssignedPerson) {
        this.$confirm(this.$t('courseScoreMana.hasAssignedPerson'), this.$t('scoreMangementBase.prompt'), {
          confirmButtonText: this.$t('scoreMangementBase.confirm'),
          cancelButtonText: this.$t('scoreMangementBase.cancel'),
          type: 'warning'
        }).then(() => {
          this.title = this.$t('courseScoreMana.designatedEntry')
          this.dialogVisible = true
        }).catch(e => {
          
        })
      } else {
        // 若勾选的数据已经有指定录入人，二次弹框确认
        if (alreadyAssigned) {
          this.settingEnterPerson = true
        } else {
          this.title = this.$t('courseScoreMana.designatedEntry')
          this.dialogVisible = true
        }
      }
    },
    // 取消指定
    cancelPoint() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 勾选数据中存在部分发布课程，则指定录入人失败，弹出“勾选课程中存在成绩已发布，不能指定录入人”
      let hasPartlyReleased = false
      // 若勾选数据中存在录入人
      let hasAssignedPerson = false
      // 勾选数据中包含指定录入人为空的数据，无法取消指定
      let hasBlankEntryPerson = false
      this.multipleSelection.forEach(value => {
        if (!value.assignedCode) {
          hasBlankEntryPerson = true
        }
        if (value.releaseNum > 0) {
          hasPartlyReleased = true
        }
        if (value.importUserName) {
          hasAssignedPerson = true
        }
      })
      // 勾选数据中包含指定录入人为空的数据，无法取消指定
      if (hasBlankEntryPerson) {
        this.$message.warning(this.$t('courseScoreMana.hasBlankEntryPerson'))
        return
      }
      // 勾选数据中存在部分发布课程，则取消指定录入人失败，弹出“勾选数据中存在成绩已发布，不能取消指定录入人”
      if (hasPartlyReleased) {
        this.$message.warning(this.$t('courseScoreMana.hasPartReleaseNotCancel'))
        return
      }
      if (hasAssignedPerson) {
        this.$confirm(this.$t('courseScoreMana.hasAssignedPersonNotCancel'), this.$t('scoreMangementBase.prompt'), {
          confirmButtonText: this.$t('scoreMangementBase.confirm'),
          cancelButtonText: this.$t('scoreMangementBase.cancel'),
          type: 'warning'
        }).then(() => {
          let teachingClassIds = this.multipleSelection.map(value => {
            return value.teachingClassId
          })
          let params = {
            "teachingClassIdList": teachingClassIds,
            "importType": "Normal",
            "assignedCode": "",
            "assignedName": ""
          }
          scoreManagementApi.cancelDesignatedEntry(params).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.cancelPointSuccessfully')
              })
              this.onSubmit()
            }
          })
        }).catch(e => {
          
        })
      } else {
        let teachingClassIds = this.multipleSelection.map(value => {
          return value.teachingClassId
        })
        let params = {
          "teachingClassIdList": teachingClassIds,
          "importType": "Normal",
          "assignedCode": "",
          "assignedName": ""
        }
        scoreManagementApi.cancelDesignatedEntry(params).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success', 
              message: this.$t('scoreMangementBase.cancelPointSuccessfully')
            })
            this.onSubmit()
          }
        })
      }
    },
    // 空白登分表
    blankScoreTable() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 只能勾选一条
      if (this.multipleSelection.length > 1) {
        this.$message.warning(this.$t('scoreMangementBase.onlyChooseOne'))
        return
      }
      this.detailInfo = {
        "calendarId": this.multipleSelection[0].calendarId,
        "examType": "2",
        "teachingClassId": this.multipleSelection[0].teachingClassId,
        "faculty": this.multipleSelection[0].faculty,
        "campus": this.multipleSelection[0].campus,
        "isBlank": "Y"
      }
      // 勾选一条的场景
      this.indexKey = 3
    },
    // 查看
    selectCourseInfo(row) {
      this.detailInfo = {
        "calendarId": row.calendarId,
        "examType": "2",
        "teachingClassId": row.teachingClassId,
        "faculty": row.faculty,
        "campus": row.campus
      }
      this.indexKey = 4
    },
    // 总评成绩表
    totalEvalScoreSheet() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 只能勾选一条
      if (this.multipleSelection.length > 1) {
        this.$message.warning(this.$t('scoreMangementBase.onlyChooseOne'))
        return
      }
      this.detailInfo = {
        "calendarId": this.multipleSelection[0].calendarId,
        "examType": "2",
        "teachingClassId": this.multipleSelection[0].teachingClassId,
        "faculty": this.multipleSelection[0].faculty,
        "campus": this.multipleSelection[0].campus
      }
      this.indexKey = 5
    },
    // 总评成绩表（分项）
    subEvalScoreSheet() {
      // 不勾选场景
      if (this.multipleSelection.length === 0) {
        this.$message.warning(this.$t('scoreMangementBase.pleaseChooseOne'))
        return
      }
      // 只能勾选一条
      if (this.multipleSelection.length > 1) {
        this.$message.warning(this.$t('scoreMangementBase.onlyChooseOne'))
        return
      }
      this.detailInfo = {
        "calendarId": this.multipleSelection[0].calendarId,
        "examType": "2",
        "teachingClassId": this.multipleSelection[0].teachingClassId,
        "faculty": this.multipleSelection[0].faculty,
        "campus": this.multipleSelection[0].campus
      }
      this.indexKey = 6
    },
    refreshMainPage() {
      this.multipleSelection = []
      this.indexKey = 1
      this.onSubmit()
    },
    // 关闭前回调
    beforeClose() {
      this.cancel()
    },
    // 调用教师接口获取相应信息通过教师姓名或ID
    teacherRemoteMethod(query) {
      if (query !== '') {
        this.loading = true
        let lang = this.$store.getters.language
        findTeacherList({ condition: query }).then(res => {
          this.loading = false;
          if (res.code == 200) {
            const list = res.data.list ? res.data.list : []
            this.options.teacherList = list.map(e => {
              return {
                value: e.code,
                facultyI18n: e.facultyI18n,
                label: lang === 'cn' ? e.name : e.nameEn,
                type: e.type
              }
            })
          }
        })
      } else {
        this.options.teacherList = []
      }
    },
    // 指定录入人二次确认
    confirmSettingEnterPerson() {
      this.dialogForm.selectTeacherName = ''
      this.options.teacherList = []
      this.settingEnterPerson = false
      this.title = this.$t('courseScoreMana.designatedEntry')
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      Object.keys(this.dialogForm).forEach(key => this.dialogForm[key] = '')
      this.$refs['dialogForm'].clearValidate()
    },
    // 确定
    confirm() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let filterTeacherInfo = this.options.teacherList.find(item => {
            return item.value === this.dialogForm.selectTeacherName
          })
          let teachingClassIds = this.multipleSelection.map(value => {
            return value.teachingClassId
          })
          let courseCodeList = this.multipleSelection.map(value => {
            return value.courseCode
          })
          let params = {
            "teachingClassIdList": teachingClassIds,
            "importType": "Normal",
            "courseCodeList": courseCodeList,
            "assignedCode": filterTeacherInfo.value,
            "assignedName": filterTeacherInfo.label,
            "assignedType": filterTeacherInfo.type
          }
          scoreManagementApi.pointDesignatedEntry(params).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.pointSuccessfully')
              })
              this.cancel()
              this.onSubmit()
            }
          })
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      })
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            // 部分发布课程
            if (item.authCode === 'courseScoreMana-partReleaseCourse') {
              this.permitToPartReleased = true;
            }
            // 指定录入人
            if (item.authCode === 'courseScoreMana-designated-entry') {
              this.permitToDesignatedEntry = true;
            }
            // 取消指定
            if (item.authCode === 'courseScoreMana-unassign') {
              this.permitToCancelPoint = true;
            }
            // 空白登分表
            if (item.authCode === 'courseScoreMana-blankScoreSheet') {
              this.permitToBlankScoreTable = true;
            }
            // 查看
            if (item.authCode === 'courseScoreMana-select') {
              this.permitToDetail = true;
            }
            // 总评成绩表
            if (item.authCode === 'courseScoreMana-overall-assess') {
              this.permitToTotalEvalScoreSheet = true;
            }
            // 总评成绩表（分项）
            if (item.authCode === 'courseScoreMana-overall-eval-sub') {
              this.permitToSubTotalEvalScoreSheet = true;
            }
            // 取消发布
            if (item.authCode === 'courseScoreMana-unPublish') {
              this.permitToUnpublish = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .condition-card ::v-deep {
    .el-row {
      height: 30px!important;
    }
    .el-form-item {
      margin-bottom: 0!important;
    }
  }
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }

</style>